package de.hs_zigr.inf.iib08gruppe5powerfish.it.control;

import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.Database;
import org.xmldb.api.base.Resource;
import org.xmldb.api.base.ResourceIterator;
import org.xmldb.api.base.ResourceSet;
import org.xmldb.api.base.XMLDBException;
import org.xmldb.api.modules.XPathQueryService;

/**
 * to get access to the eXist-DB
 */
public class CtrlEXistDriver {

	private Class cl;
	private Database database;
	private Collection col;
	private XPathQueryService service;
	
	/**
	 * to setup DB-Connection
	 * @throws ClassNotFoundException 
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 * @throws XMLDBException 
	 */
	public void setUpDBConnection(String strDriver, String strCollection) throws ClassNotFoundException, InstantiationException, IllegalAccessException, XMLDBException{
		// strDriver = "org.exist.xmldb.DatabaseImpl";
		cl = Class.forName(strDriver);
		database = (Database) cl.newInstance();
		DatabaseManager.registerDatabase(database);
		// p.e. strCollection == "xmldb:exist://localhost:8080/exist/xmlrpc/db/test"
		col = DatabaseManager.getCollection(strCollection);
		service = (XPathQueryService) col
				.getService("XPathQueryService", "1.0");
		service.setProperty("indent", "yes");
	}

	/**
	 * to get the resultSet for a committed XQuery
	 * 
	 * @param query: committed XQuery
	 * @return resultSet for query
	 * @throws XMLDBException
	 */
	public String getResultSet(String query) throws XMLDBException {
		String strResult = "";
		String strQuery = query;
		ResourceSet result = service.query(strQuery);
		ResourceIterator i = result.getIterator();
		while (i.hasMoreResources()) {
			Resource r = i.nextResource();
			strResult = strResult + (String) r.getContent() + "\n";
		}
		return strResult;
	}
}